using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;


namespace FUSE
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class Player : GameComponent
    {
        //Statistics
        //Max values
        public double maxSpeed = 0;
        public double maxFuel = 0;
        public double maxArmor = 0;
        public double maxHealth = 0;
        protected string shipName = "";
        protected string shipTexture = "";
        protected String username = "Fry";
        public int maxLives = 5;
        //Current values
        public double currentScore = 0d;
        public double totalHighScore = 0d;
        protected double stageStartTime = 0;
        protected string currentTimeElapsed="Unknown"; //may need to get this from galaxy

        protected double currentComboCount = 0;
        protected double currentStage = 0;
        protected MapGenerator.Difficulty currentStageDifficulty = MapGenerator.Difficulty.Tutorial;
        protected MapGenerator.Difficulty selectedDifficulty = MapGenerator.Difficulty.Noob;

        //Positions
        //Top Left
        private Vector2 currentScorePosition ;
        private Vector2 currentTimeElapsedPosition;
        private Vector2 currentComboPosition;

        //Top Right
        private Vector2 currentStagePosition;
        private Vector2 currentStageDifficultyPosition;

        //Bottom Right
        public Vector2 currentArmorPosition;
        public Vector2 currentHealthPosition;

        //Bottom Left
        private Vector2 currentSpeedPosition;
        public Vector2 currentFuelPosition;
        private Vector2 currentLivesLeftPosition;
        private int attributePosition;

        public Vector2 currentLaunchPosition;

        //Bottom Mid-Right
        private Vector2 usernamePosition;
        //Player's Ship

        //Player's ship
        public Ship ship;

        //GUI attributes
        public const String SCORE_FONT = "scoreFont";
        public const String TITLE_FONT = "statTitleFont";
        public const String LIFE_IMAGE = "NormalShipRoughSmall";
        
        private SpriteFont scoreFont;
        private SpriteFont statTitleFont;
        
        //Textures
        protected Texture2D lifeTexture;
        protected Texture2D launchBar;

        //Timer
        public Timer timer;
        public DateTime startTime;
        public DateTime pausedTime;
        public TimeSpan elapsedTime;
        private Boolean isPaused = false;

        public int armorBonus;
        public int fuelBonus;
        public int healthBonus;
        public int timeBonus;
        public int totalBonus;


        public Player(Game game)
            : base(game)
        {

            ContentManager content = Game.Content;
            // Load game font
            scoreFont = content.Load<SpriteFont>(SCORE_FONT);
            statTitleFont = content.Load<SpriteFont>(TITLE_FONT);
            lifeTexture = content.Load<Texture2D>(LIFE_IMAGE);


            int leftX = 10;
            int rightX = 500;
            int topY = 5;
            int bottomY = 560;
            //Top Left

            currentScorePosition = new Vector2(leftX, topY);
            currentTimeElapsedPosition = new Vector2(leftX, topY+20);
            currentComboPosition = new Vector2(leftX, topY+40);

            //Top Right
            currentStagePosition = new Vector2(rightX, topY);//(Game.GraphicsDevice.Viewport.Width-10)
            currentStageDifficultyPosition = new Vector2(rightX, topY + 20);

            //Bottom Right
            currentArmorPosition = new Vector2(rightX-50, bottomY-5);
            currentHealthPosition = new Vector2(rightX-50, (bottomY-20));

            //Bottom Left
            currentSpeedPosition = new Vector2(leftX, (bottomY-5));
            currentFuelPosition = new Vector2(leftX, (bottomY-20));
            currentLaunchPosition = new Vector2(leftX, 575);
            currentLivesLeftPosition = new Vector2(leftX, (bottomY - 45));

            //Bottom Mid-Right
            usernamePosition = new Vector2(rightX-150, (bottomY-5));

            this.startTime = DateTime.Now;
            this.currentTimeElapsed = getTime();
            this.currentStage = 0;
            this.currentStageDifficulty = MapGenerator.Difficulty.Noob;

            timer = new Timer();
            startTime = new DateTime();
            ship = new Ship(game);
            // TODO: Construct any child components here
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            

            base.Initialize();
        }
        /// <summary>
        /// Use to reInitialize players stats for beginning of each stage
        /// </summary>
        /// <param name="gotStage"></param>
        /// <param name="gotStartTime"></param>
        public void reInitialize(int gotStage)
        {
            currentStage = gotStage;
            
            startTime = DateTime.Now;
            currentTimeElapsed = getTime(); //should be all 0
            totalHighScore = 0;
            currentScore = 0;
            currentComboCount = 0;

        }
        public void startTimer()
        {

            if (timer != null)
            {
                stopTimer();
                startTime = DateTime.Now;
            }
            timer = new Timer();
            timer.Enabled = true;
            timer.Interval = 100; //1000 milliseconds to second
            timer.Elapsed += new ElapsedEventHandler(Timer_Tick);

            timer.Start();
        }

        public void pauseTimer()
        {
            if (timer.Enabled)
            {
                timer.Stop();
                pausedTime = DateTime.Now;
                this.isPaused = true;
            }
        }

        public void unpauseTimer()
        {
            if (this.isPaused)
            {
                TimeSpan difference = (DateTime.Now.Subtract(pausedTime));
                startTime = startTime.Add(difference);
                this.isPaused = false;
                timer.Start();
            }
        }

        public void stopTimer()
        {
            timer.Stop();
            timer.Dispose();
            this.startTime = DateTime.Now;
            this.currentTimeElapsed = getTime();
        }
        /// <summary>
        /// Reinitialize ship conditions inside build screen
        /// </summary>
        /// <param name="gotMaxArmor"></param>
        /// <param name="gotMaxHealth"></param>
        /// <param name="gotMaxSpeed"></param>
        /// <param name="gotMaxFuel"></param>
        public void setPlayerConditions(double gotMaxArmor, double gotMaxHealth, double gotMaxSpeed, double gotMaxFuel, int gotMaxLives)
        {
            this.maxArmor = gotMaxArmor;
            this.maxHealth = gotMaxHealth;
            this.maxSpeed = gotMaxSpeed;
            this.maxFuel = gotMaxFuel;
            maxLives = gotMaxLives;
            //Initialize ship
            ship.setShipConditions(maxArmor, maxHealth, maxSpeed, maxFuel, maxLives);
        }
        /// <summary>
        /// Draws the player's statistics on gameplay screen
        /// </summary>
        /// <param name="spriteBatch"></param>
        public void Draw(SpriteBatch spriteBatch)
        {
            //spriteBatch.Draw(launchBar, new Rectangle(10, 575, (int)(currentLaunchVelocity * 2 / maxLaunchVelocity * 100), 20), new Rectangle(0, 45, 200, 20), Color.Red);
            //Top Left
            spriteBatch.DrawString(scoreFont, "Score: " + (currentScore/*+totalHighScore*/).ToString(), currentScorePosition, Color.Yellow);

            spriteBatch.DrawString(scoreFont, "Elapsed Time: " + currentTimeElapsed.ToString(), currentTimeElapsedPosition, Color.LightSalmon);
            //spriteBatch.DrawString(scoreFont, "Combos: " + currentComboCount.ToString(), currentComboPosition, Color.LightCyan);
            //Top Right
            spriteBatch.DrawString(scoreFont, "Stage: " + currentStage.ToString(), currentStagePosition, Color.WhiteSmoke);
            spriteBatch.DrawString(scoreFont, "Difficulty: " + currentStageDifficulty.ToString(), currentStageDifficultyPosition, Color.WhiteSmoke);
            //Bottom right
            //spriteBatch.Draw(launchBar, new Rectangle(currentArmorPosition.X, currentArmorPosition.Y, (int)(50), 20), Color.Orange);
            spriteBatch.DrawString(scoreFont, "Armour: " /*+ (int)ship.currentArmor*/, currentArmorPosition, Color.Orange);
            spriteBatch.DrawString(scoreFont, "Health: " /*+ (int)ship.currentHealth*/, currentHealthPosition, Color.PaleVioletRed);
            spriteBatch.DrawString(scoreFont, "Launch: ", currentLaunchPosition, Color.Red);
            //Bottom Left
            //@HACK
            String currentSpeed;
            if (ship.currentSpeed.ToString().Length > 6)
            {
                currentSpeed = ship.currentSpeed.ToString().Substring(0, 4);
            }
            else
            {
                currentSpeed = ship.currentSpeed.ToString();
            }
            spriteBatch.DrawString(scoreFont, "Speed: Warp " + currentSpeed, currentSpeedPosition, Color.LightGoldenrodYellow);
            spriteBatch.DrawString(scoreFont, "Fuel: " /*+ (int)ship.currentFuel*/, currentFuelPosition, Color.CornflowerBlue);

            //Draw the health for the health bar
            


            //Draw the box around the health bar
            //spriteBatch.Draw(launchBar, new Rectangle(20, 30, launchBar.Width, 44), new Rectangle(0, 0, launchBar.Width, 44), Color.White);

            /*
            for (int i = 0; i < ship.livesLeft; i++)
            {
 
                spriteBatch.Draw(lifeTexture, currentLivesLeftPosition, Color.Red);
                attributePosition += lifeTexture.Width-1 ; //adding space between
                currentLivesLeftPosition.X += lifeTexture.Width-1;
            }
             * */
            //ReAlign
            currentLivesLeftPosition.X -= attributePosition;
            attributePosition = 0;
                //Bottom Mid-Right
                spriteBatch.DrawString(scoreFont, "Cpt. " + username, usernamePosition, Color.CadetBlue);
        }
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
       

            base.Update(gameTime);
        }

        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            if (sender == timer)
            {
                currentTimeElapsed = getTime();
            }
        }

        public string getTime()
        {
            string TimeInString = "";
            elapsedTime = DateTime.Now.Subtract(startTime);
            if (elapsedTime.ToString().Length > 11)
            {
                TimeInString = elapsedTime.ToString().Substring(0, 11);
            }
            else
            {
                TimeInString = elapsedTime.ToString();
            }
            
            return TimeInString;
        }

        public void LoadShipFile(string name, int armor, int fuel, int speed, string texture)
        {
            
            
            //loadedShips = new ShipData(name, armor, fuel, speed, texture);
            shipName = name;
            maxArmor = armor;
            maxFuel = fuel;
            maxSpeed = speed;
            ship.sTexture = texture;
             

        }

        public void incrementCurrentStage()
        {
            this.currentStage++;
        }

        public MapGenerator.Difficulty CurrentStageDifficulty
        {
            get { return this.currentStageDifficulty; }
            set { this.currentStageDifficulty = value; }
        }

        public MapGenerator.Difficulty SelectedDifficulty
        {
            get { return this.selectedDifficulty; }
            set { this.selectedDifficulty = value; }
        }

        public int StageCount
        {
            get { return (int)this.currentStage; }
        }

        public Vector2 ArmourTextPosition
        {
            get { return this.currentArmorPosition; }
        }

        public Vector2 HealthTextPosition
        {
            get { return this.currentHealthPosition; }
        }

        public Vector2 FuelTextPosition
        {
            get { return this.currentFuelPosition; }
        }

        public Vector2 LaunchTextPosition
        {
            get { return this.currentLaunchPosition; }
        }
    }
}
